package com.chengww.grab_rp.service

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.chengww.grab_rp.api.NetworkManager
import com.chengww.grab_rp.api.PluginService
import com.chengww.grab_rp.api.RequestBody
import com.chengww.grab_rp.database.AppDatabase
import com.chengww.grab_rp.database.redpocket.RedPocket
import com.chengww.grab_rp.database.redpocket.RedPocketDao
import com.chengww.grab_rp.database.user.UserDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Created by chengww on 2/20/21
 * @author chengww
 */
class GrabBroadcastReceiver : BroadcastReceiver() {

    private val service: PluginService by lazy { NetworkManager.pluginService }
    private var userDao: UserDao? = null
    private var redPocketDao: RedPocketDao? = null

    override fun onReceive(context: Context, intent: Intent) {
        if (userDao == null) userDao = UserDao.getInstance(context)
        if (redPocketDao == null) redPocketDao = AppDatabase.getInstance(context).redPocketDao()

        when(intent.getStringExtra(ACTION)) {
            ACTION_GRAB -> {
                val rpSn = intent.getStringExtra(ITEM_RP_SN)
                if (rpSn.isNullOrEmpty()) return
                val teamId = intent.getStringExtra(ITEM_TEAM_ID)
                if (teamId.isNullOrEmpty()) return
                val amount = intent.getIntExtra(ITEM_AMOUNT, 0)
                val teamName = intent.getStringExtra(ITEM_TEAM_NAME)

                GlobalScope.launch(Dispatchers.IO) {
                    val user = userDao?.getUser() ?: return@launch
                    val body = RequestBody().put("plugid", user.plugId).put("token", user.token)
                        .put("redpacket_sn", rpSn).sign(user.md5Key)
                    val result = runCatching {
                        service.done(body)
                    }.getOrNull()
                    if (result == null || !result.isSuccess()) {
                        redPocketDao?.insert(RedPocket(rpSn, teamId, amount, teamName ?: "", false))
                    } else {
                        redPocketDao?.insert(RedPocket(rpSn, teamId, amount, teamName ?: "", true))
                    }
                }
            }

            ACTION_IS_SERVICE_ONLINE -> {
                GlobalScope.launch(Dispatchers.IO) {
                    val user = userDao?.getUser()
                    if (user != null) {
                        intent.putExtra(ACTION_IS_SERVICE_ONLINE, user.token)
                    } else {
                        intent.putExtra(ACTION_IS_SERVICE_ONLINE, "")
                    }
                    withContext(Dispatchers.Main) {
                        intent.action = INTENT_ACTION_APP
                        context.sendBroadcast(intent, PERMISSION)
                    }
                }
            }
        }
    }

    companion object {
        private const val ACTION = "action"
        private const val ACTION_IS_SERVICE_ONLINE = "action_is_service_online"
        private const val ACTION_GRAB = "action_grab"
        const val PERMISSION = "com.chengww.grab_rp.permission.grab"

        private const val ITEM_RP_SN = "item_rp_sn"
        private const val ITEM_TEAM_ID = "item_team_id"
        private const val ITEM_AMOUNT = "item_amount"
        private const val ITEM_TEAM_NAME = "item_team_name"
        private const val INTENT_ACTION_APP = "com.chengww.grab_rp.app"
    }
}